package com.qlylkj.lbk.ui.company

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.bumptech.glide.request.RequestOptions
import com.forest.core.etx.load
import com.forest.core.etx.startKtxActivity
import com.forest.core.etx.toast
import com.forest.core.widget.dialog.FDialog
import com.forest.core.widget.dialog.FDialogInterface
import com.forest.core.widget.dialog.Options
import com.jeremyliao.liveeventbus.LiveEventBus
import com.qlylkj.lbk.R
import com.qlylkj.lbk.app.PreferenceHelper
import com.qlylkj.lbk.app.addHost
import com.qlylkj.lbk.base.BaseVMFragment
import com.qlylkj.lbk.model.bean.Company
import com.qlylkj.lbk.model.event.LiveEvent
import com.qlylkj.lbk.ui.user.authentication.IdentityAuthActivity
import com.qlylkj.lbk.ui.user.login.LoginActivity
import kotlinx.android.synthetic.main.fragment_company_info.*

class CompanyInfoFragment : BaseVMFragment<CompanyViewModel>() {

    companion object {

        private const val COMPANY_ID = "companyId"

        fun newInstance(companyId: String = ""): CompanyInfoFragment {
            val instance = CompanyInfoFragment()
            instance.arguments = Bundle().apply {
                putString(COMPANY_ID, companyId)
            }
            return instance
        }
    }

    private var mCompany: Company? = null

    override fun providerVMClass() = CompanyViewModel::class.java

    override fun setLayoutId() = R.layout.fragment_company_info

    override fun initView() {
        companyNameText.setOnClickListener(onClickListener)
        authText.setOnClickListener(onClickListener)
        coChainText.setOnClickListener(onClickListener)
    }

    private fun setCompanyView() {
        mCompany?.apply {
            activity?.run {
                companyCoverImage.load(
                    this,
                    faceImg.addHost(),
                    RequestOptions().placeholder(R.mipmap.ic_company_cover_default)
                )
            }
            companyNameText.text = companyName
            checkStatusText.text = when (checkStatus) {
                1 -> "待审核"
                2 -> "待上链"
                3 -> "未通过"
                4 -> "上链中"
                5 -> "上链成功"
                6 -> "上链失败"
                else -> ""
            }
            companyStatusText.text = registrationStatus
            applyStatusText.text = when (bindingStatus) {
                -1 -> "未认证"
                0 -> "认证中"
                1 -> "已认证"
                else -> "未认证"
            }
            authText.isVisible = bindingStatus == -1
            coChainText.isVisible = checkStatus == 2 && bindingStatus == 1
            companyLegalPersonText.text = legalPersonInfo
            companyRegistrationTimeText.text = establishDate
            companyRegisterDateText.text = establishDate
            registrationStatusText.text = registrationStatus
            registerCapitalText.text = "${registeredCapital}人民币"
            companyTypeText.text = companyType
            companyAddressText.text = address
            unifiedSocialCreditCodeText.text = creditCode
            taxpayerIdentificationCodeText.text = ein
            businessRegistrationNumberText.text = registrationNumber
            organizationCodeText.text = organizationCode
            businessScopeContentText.text = businessScope
            companyPhoneNumberText.text = cphone
            landLineNumberText.text = telphone
            weiBoNameText.text = microblog ?: "暂无微博"
            weChatOfficialAccountText.text = officialAccounts ?: "暂无微信公众号"
            companyOfficialWebsiteText.text = website
            companyProfileText.text = companyProfile
            developmentHistoryContentText.text = development
        }
    }

    override fun initData() {

    }

    override fun onResume() {
        super.onResume()
        getCompanyInfo()
    }

    override fun startObserve() {
        super.startObserve()
        mViewModel.apply {
            uiState.observe(this@CompanyInfoFragment, Observer { uiModel ->
                uiModel?.run {
                    company?.let {
                        mCompany = it
                        setCompanyView()
                    }
                    if (companyFromCoChainSuccess) {
                        getCompanyInfo()
                    }
                    showError?.let {
                        activity?.toast(it)
                    }
                }
            })
        }
    }

    private val onClickListener = View.OnClickListener {
        when (it.id) {
            R.id.companyNameText -> toEditCompanyInfo()
            R.id.authText -> toIdentityAuth()
            R.id.coChainText -> companyCoChain()
            else -> {
            }
        }
    }

    private fun getCompanyInfo() {
        val companyId = arguments?.getString(COMPANY_ID) ?: ""
        if (companyId.isEmpty()) {
            PreferenceHelper.getUserInfo({ userInfo ->
                userInfo.consumersId?.let {
                    if (it.isNotEmpty()) {
                        mViewModel.getCompanyInfo(it)
                    }
                }
            })
        } else {
            mViewModel.getCompanyInfo(companyId)
        }
    }

    private fun companyCoChain() {
        mCompany?.apply {
            if (PreferenceHelper.isLogin) {
                PreferenceHelper.getUserInfo({
                    if (it.consumersId == id) {
                        mViewModel.companyFromCoChain(id)
                    } else {
                        activity?.toast("这不是你身份认证所绑定的公司,无法进行上链。")
                    }
                })
            } else {
                showToLoginDialog("上链需要先登录并通过身份验证才能进行后续操作,赶快去登录吧。")
            }
        }
    }

    private fun showToLoginDialog(message: String) {
        activity?.run {
            FDialog.newInstance().apply {
                options = Options().apply {
                    isTransparent = true
                }
                setOnDismissListener(object : FDialogInterface.OnDismissListener {
                    override fun onDismiss(dialog: FDialogInterface) {

                    }
                })
                setOnBuilderViewListener(object : FDialogInterface.OnBuilderViewListener {
                    override fun onBuilderView(
                        dialog: FDialogInterface,
                        view: View,
                        layoutRes: Int
                    ) {
                        val titleText = view.findViewById<TextView>(R.id.titleText)
                        val messageText = view.findViewById<TextView>(R.id.messageText)
                        val negativeText = view.findViewById<TextView>(R.id.negativeText)
                        val positiveText = view.findViewById<TextView>(R.id.positiveText)
                        titleText.text = "系统提示"
                        messageText.text = message
                        negativeText.text = "取消"
                        positiveText.text = "去登录"
                        positiveText.setOnClickListener {
                            dialog.dismiss()
                            startKtxActivity<LoginActivity>()
                        }

                        negativeText.setOnClickListener {
                            dialog.dismiss()
                        }
                    }
                })
                show(supportFragmentManager, "toLogin")
            }
        }
    }

    private fun toEditCompanyInfo() {
        if (PreferenceHelper.isLogin) {
            PreferenceHelper.getUserInfo({
                mCompany?.apply {
                    if (it.consumersId == id) {
                        LiveEventBus.get(LiveEvent.EDIT_COMPANY_INFO_KEY).post(this)
                        startKtxActivity<EditCompanyInfoActivity>(value = EditCompanyInfoActivity.EDIT_COMPANY_INFO to true)
                    }else{
                        activity?.toast("该企业不是你认证的企业,无法编辑信息。")
                    }
                }
            })
        }else{
            showToLoginDialog("编辑公司信息需要先登录,赶快去登录吧。")
        }
    }

    private fun toIdentityAuth() {
        mCompany?.apply {
            if (PreferenceHelper.isLogin) {
                PreferenceHelper.getUserInfo({
                    if (it.bindingStatus == 1) {
                        activity?.toast("你已进行过身份认证。")
                    } else {
                        LiveEventBus.get(LiveEvent.SELECT_COMPANY_KEY).post(this)
                        startKtxActivity<IdentityAuthActivity>()
                    }
                })
            } else {
                showToLoginDialog("认证需要先登录才能进行后续操作,赶快去登录吧。")
            }
        }

    }

}